<?php
	/* Este archivo contiene la clase SQLdb que permite un uso siemple de la base de datos (MySQL)	*/

	define("CONF_FILE", "conf/setup.ini");

	class SQLdb
	{
		private $server;
		private $user;
		private $pass;
		private $database;
		private $desc;

		public $res;

		function __construct($user, $pass)
		{

			$this->user = $user;
			$this->pass = $pass;
			$this->server = "localhost";
			$this->database = "gradodos";
			$this->connect();
		}

		private function connect()
		{
			$this->desc = mysql_connect($this->server, $this->user, $this->pass) or die("Error al conectarse a la base de datos: " . mysql_error());

			mysql_select_db($this->database, $this->desc);
		}

		public function query($string)
		{
			$this->res = mysql_query($string, $this->desc);// or die("Error al realizar la consulta: " . mysql_error());
		}

		public function get_row()
		{
			$res = false;
			if($this->res && mysql_num_rows($this->res) > 0)
			{
				if($row = mysql_fetch_array($this->res, MYSQL_ASSOC))
					$res = $row;
			}

			return $res;
		}

		public function query_array($string)
		{
			$i = 0;
			$j = 0;

			$this->query($string);

			$res_tmp = $this->get_row();
			while($res_tmp)
			{
				$res[$i] = $res_tmp;
				$res_tmp = $this->get_row();

				$i++;
			}

			return $res;
		}

		public function show_query($string)
		{
			$this->query($string);

			$row = $this->get_row();

			echo "<table border=1 align=\"center\">";
			echo "<tr>";
			foreach($this->get_keys() as $index => $value)	
				echo "<td> $value </td>";
			echo "</tr>";

			while($row)
			{
				echo "<tr>";
				foreach($row as $value)	
					echo "<td>$value</td>";
				echo "</tr>";

				$row = $this->get_row();
			}

			echo "</table>";

		}

		public function get_rows()
		{
			$res = $this->res ? mysql_num_rows($this->res) : false;
			return $res;
		}

		public function get_fields()
		{
			$res = $this->res ? mysql_num_fields($this->res) : false;
			return $res;
		}	

		public function get_keys()
		{
			$fields = $this->get_fields();
			if($this->res && $fields)
			{			
				for($i = 0; $i < $fields; $i++)
					$keys[$i] = mysql_field_name($this->res, $i);
			}
			else
				$keys = false;

			return $keys;
		}

		function __destruct()
		{
		
			mysql_close();
		}


				
	};
?>
